<template>
  <div class="comment-item">
    <div class="comment-header">
      <img :src="userInfo.avatar" alt="头像" class="avatar" @click="goToUserPage(props.comment.userId)" style="cursor: pointer;" />
      <span class="comment-user" @click="goToUserPage(props.comment.userId)" style="cursor: pointer;">{{ userInfo.nickname }}</span>
      <span class="comment-date">{{ formatDate(comment.createDate) }}</span>
      <button class="reply-btn" @click="showReply = !showReply">回复</button>
    </div>
    <div class="comment-content">
      <span>{{ comment.content }}</span>
    </div>
    <div v-if="showReply" class="reply-input-row">
      <input v-model="replyContent" placeholder="写下你的回复..." class="reply-input" @keyup.enter="submitReply" />
      <button class="reply-submit-btn" @click="submitReply" :disabled="!replyContent.trim()">发送</button>
    </div>
    <div v-if="subComments.length" class="sub-comment-list">
      <div v-for="sub in subComments" :key="sub.id" class="sub-comment-item">
        <div class="sub-comment-header">
          <img :src="getSubCommentUserInfo(sub.userId).avatar" alt="头像" class="sub-avatar" @click="goToUserPage(sub.userId)" style="cursor: pointer;" />
          <span class="sub-comment-user" @click="goToUserPage(sub.userId)" style="cursor: pointer;">{{ getSubCommentUserInfo(sub.userId).nickname }}</span>
          <span class="sub-comment-date">{{ formatDate(sub.createDate) }}</span>
          <button class="reply-btn" @click="showSubReply[sub.id] = !showSubReply[sub.id]">回复</button>
        </div>
        <div class="sub-comment-content">
          <template v-if="isQuotedReply(sub.content)">
            <span class="quote-reference">{{ getQuoteReference(sub.content) }}</span>
            <span>{{ getActualContent(sub.content) }}</span>
          </template>
          <template v-else>
            {{ sub.content }}
          </template>
        </div>
        <div v-if="showSubReply[sub.id]" class="reply-input-row">
          <input v-model="subReplyContent[sub.id]" placeholder="写下你的回复..." class="reply-input" @keyup.enter="() => submitSubReply(sub)" />
          <button class="reply-submit-btn" @click="() => submitSubReply(sub)" :disabled="!subReplyContent[sub.id]?.trim()">发送</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import axios from 'axios';
import { currentUser } from '../user';
import { useRouter } from 'vue-router';
const router = useRouter();

// 跳转到用户主页
function goToUserPage(userId) {
  if (userId) {
    router.push(`/user/${userId}`);
  }
}
const props = defineProps({
  comment: { type: Object, required: true },
  allComments: { type: Array, default: () => [] }
});

const getUserId = () => currentUser.id || Number(localStorage.getItem('userId')) || 4;

// 用户信息缓存
const userCache = reactive({});

// 获取用户信息（支持缓存）
async function getUserInfo(userId) {
  if (userCache[userId]) return userCache[userId];

  try {
    const res = await axios.get(`http://localhost:8084/api/user/${userId}`);
    const data = res.data;

    // 确保 nickname 和 avatar 存在
    const nickname = data.nickname || '匿名用户';
    const avatar = data.avatar || 'https://example.com/avatars/guest1.jpg';

    const info = {nickname, avatar};
    userCache[userId] = info;
    return info;
  } catch (error) {
    console.warn('Failed to fetch user info:', error);
    return {nickname: '匿名用户', avatar: 'https://example.com/avatars/guest1.jpg'};
  }
}

// 主评论用户信息
const userInfo = ref({
  nickname: '匿名用户',
  avatar: 'https://example.com/avatars/guest1.jpg'
});

// 子评论用户信息缓存
const subCommentUserInfos = reactive({});

// 控制子评论回复框显隐
const showSubReply = reactive({});
const subReplyContent = reactive({});

// 加载主评论用户信息
onMounted(async () => {
  if (!props.comment.userId) return;

  try {
    const info = await getUserInfo(props.comment.userId);
    userInfo.value = info;
  } catch (error) {
    console.warn('Failed to fetch user info:', error);
    userInfo.value = {nickname: '匿名用户', avatar: 'https://example.com/avatars/guest1.jpg'};
  }
});


// 格式化日期
function formatDate(date) {
  if (!date) return '';
  const d = new Date(date);
  return d.toLocaleString();
}

// 判断是否为引用回复
function isQuotedReply(content) {
  return content.startsWith('@') && content.includes('\n');
}

function getQuoteReference(content) {
  if (!isQuotedReply(content)) return '';
  return content.split('\n')[0];
}

function getActualContent(content) {
  if (!isQuotedReply(content)) return content;
  return content.split('\n').slice(1).join('\n');
}

// 子评论数据
const subComments = ref([]);

// 加载子评论
async function fetchSubComments() {
  try {
    const response = await axios.get(`http://localhost:8085/comments/parent/${props.comment.id}`);
    subComments.value = response.data;

    for (const sub of subComments.value) {
      if (sub.userId && !subCommentUserInfos[sub.userId]) {
        try {
          const res = await axios.get(`http://localhost:8084/api/user/${sub.userId}`);
          subCommentUserInfos[sub.userId] = {
            nickname: res.data.nickname || '匿名用户',
            avatar: res.data.avatar || 'https://example.com/avatars/guest1.jpg'
          };
        } catch {
          subCommentUserInfos[sub.userId] = {
            nickname: '匿名用户',
            avatar: 'https://example.com/avatars/guest1.jpg'
          };
        }
      }
    }
  } catch {
    subComments.value = [];
  }
}

onMounted(fetchSubComments);

function getSubCommentUserInfo(userId) {
  return subCommentUserInfos[userId] || {nickname: '匿名用户', avatar: 'https://example.com/avatars/guest1.jpg'};
}

// 提交主评论回复
const showReply = ref(false);
const replyContent = ref('');

async function submitReply() {
  if (!replyContent.value.trim()) return;
  const newComment = {
    activityId: props.comment.activityId,
    userId: getUserId(),
    parentId: props.comment.id,
    content: replyContent.value,
    createDate: new Date(),
    updateDate: new Date(),
    isDeleted: 0,
    version: 1
  };
  await axios.post('http://localhost:8085/comments', newComment);
  replyContent.value = '';
  showReply.value = false;
  fetchSubComments();
}

// 提交子评论回复
async function submitSubReply(subComment) {
  const content = subReplyContent[subComment.id];
  if (!content?.trim()) return;

  const repliedUserInfo = getSubCommentUserInfo(subComment.userId);
  const repliedNickname = repliedUserInfo.nickname;

  const quotedContent = `@${repliedNickname}: ${subComment.content.substring(0, 30)}${subComment.content.length > 30 ? '...' : ''}\n${content}`;

  const newComment = {
    activityId: props.comment.activityId,
    userId: getUserId(),
    parentId: props.comment.id,
    content: quotedContent,
    createDate: new Date(),
    updateDate: new Date(),
    isDeleted: 0,
    version: 1
  };

  await axios.post('http://localhost:8085/comments', newComment);
  subReplyContent[subComment.id] = '';
  showSubReply[subComment.id] = false;
  fetchSubComments();
}
</script>

<style scoped>
.comment-item {
  background: #fff;
  border-radius: 4px;
  padding: 8px 12px;
  margin-bottom: 24px; /* 增大间距 */
  box-shadow: 0 1px 4px rgba(44, 62, 80, 0.06);
  color: #23232b;
  position: relative;
}

.comment-header {
  font-size: 12px;
  color: #888;
  margin-bottom: 12px; /* 从 2px 增至 12px */
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.comment-content {
  font-size: 14px;
  color: #23232b;
}

.reply-btn {
  background: none;
  border: none;
  color: #3498db;
  font-size: 13px;
  cursor: pointer;
  margin-left: 8px;
  padding: 2px 8px;
  border-radius: 4px;
  transition: background 0.2s, color 0.2s;
}

.reply-btn:hover {
  background: #eaf6fd;
  color: #1769aa;
}

.reply-input-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 8px 0 4px 0;
}

.reply-input {
  flex: 1;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 14px;
  background: #fff;
}

.reply-submit-btn {
  background: #3498db;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 4px 14px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.2s;
}
.reply-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-right: 8px;
  vertical-align: middle;
}

.avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  margin-right: 10px;
}
.reply-submit-btn:disabled {
  background: #bfc3c9;
  cursor: not-allowed;
}

.sub-comment-list {
  margin-top: 6px;
  margin-left: 24px;
  border-left: 2px solid #eaf6fd;
  padding-left: 12px;
}

.sub-avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  margin-right: 10px;
  vertical-align: middle;
}

.sub-comment-item {
  background: #eae8e8;
  border-radius: 4px;
  padding: 6px 10px;
  margin-bottom: 16px; /* 从 4px 增至 8px */
  box-shadow: 0 1px 2px rgba(44, 62, 80, 0.04);
}

.sub-comment-header {
  font-size: 12px;
  color: #575c5f;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.sub-comment-user {
  font-weight: bold;
  margin-right: 8px;
}

.sub-comment-date {
  color: #888;
}

.sub-comment-content {
  font-size: 14px;
  color: #23232b;
  white-space: pre-wrap;
}

.quote-reference {
  color: #181818;
  font-size: 12px;
  background-color: #f0f2f5; /* 改为灰色 */
  padding: 2px 4px;
  border-radius: 2px;
  display: block;
  margin-bottom: 4px;
}

::-webkit-scrollbar {
  width: 8px;
  background: #fff;
}

::-webkit-scrollbar-thumb {
  background: #e0e0e0;
  border-radius: 4px;
}
</style>
